package edu.msg.hrappy.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import edu.msg.hrappy.backend.model.Candidate;
import edu.msg.hrappy.backend.model.Comment;
import edu.msg.hrappy.backend.model.Job;
import edu.msg.hrappy.backend.service.CandidateService;
import edu.msg.hrappy.backend.service.JobService;
import edu.msg.hrappy.backend.service.UserService;
import edu.msg.hrappy.backend.service.util.Validator;

/**
 * Servlet implementation class AddCandidateServlet
 */

public class UpdateCandidateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	private CandidateService candidateService;
	@EJB
	private UserService userService;
	@EJB
	private JobService jobService;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UpdateCandidateServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	/*
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Candidate candidate=candidateService.getById(Long.parseLong(request.getParameter("CandidateId")));
		request.getSession().setAttribute("candidate", candidate);
		String address = "./updateCandidate.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}
	*/
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		session.setAttribute("up", request.getUserPrincipal().toString());
		Long id;
		try{
			 id=Long.parseLong(request.getParameter("candidateId"));
			 Candidate candidate=candidateService.getById(id);
			 session.setAttribute("candidate",candidate );
			 session.setAttribute("jobId", candidate.getJob().getId());
			 session.setAttribute("job", jobService.getById(candidate.getJob().getId()));
			 session.setAttribute("firstNameMesage", "");
				session.setAttribute("lastNameMesage", "");
				session.setAttribute("dateMesage", "");
				session.setAttribute("phoneNumberMesage", "");
				session.setAttribute("mobilePhoneNumberMesage",
						"");
				session.setAttribute("emailMesage", "");
			 
		}catch(Exception e) {
			
			String address = "./error.jsp";
			RequestDispatcher dispatcher = request.getRequestDispatcher(address);
			dispatcher.forward(request, response);
		}
		
		
		
		String address = "./updateCandidate.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	
	@SuppressWarnings("deprecation")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String filename = "";
		Map<String, Object> transfer = new HashMap<String, Object>();
		byte[] cv = null;
		try {
			List<FileItem> items = new ServletFileUpload(
					new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String fieldname = item.getFieldName();
					String fieldvalue = item.getString();
					transfer.put(fieldname, fieldvalue);

				} else {
					// String fieldname = item.getFieldName();
					filename = FilenameUtils.getName(item.getName());
					@SuppressWarnings("unused")
					InputStream filecontent = item.getInputStream();
					cv = item.get();
				

				}
			}
		} catch (Exception e) {
		}
		
		Long id=null;
		String firstName = "";
		String lastName = "";
		Date date = new Date();
		List<Comment> comments = new ArrayList<Comment>();
		String phoneNumber = "";
		String mobilePhoneNumber = "";
		String email = "";
		String address = "";
		Boolean relocate = false;
		String commentText = "";
		String jobId = "";
		Job job = null;
		String firstNameMesage = "";
		String lastNameMesage = "";
		String dateMesage = "";
		String phoneNumberMesage = "";
		String mobilePhoneNumberMesage = "";
		String emailMesage = "";
		String addressMesage = "";
		boolean globalOk = true;
		boolean ok = false;
		String userName="";
		int year=0;
		int month=0;
		int day=0;
		
		
		try {
			id =Long.parseLong((String) transfer.get("candidateId"));
		} catch (Exception e) {
			//error
			globalOk = false;
		}
		
		
		
		try {
			firstName = (String) transfer.get("firstName");
			ok = Validator.validateString(firstName);
			if (ok == false) {
				firstNameMesage = "Please enter a real name!<br>(minim 3 alphabetical characters)";
				globalOk = false;
			}	else {System.out.println("a");}
		} catch (Exception e) {
			firstNameMesage = "Please enter a real name!<br>(minim 3 alphabetical characters)";
			globalOk = false;
		}
		
		
		try {
			ok = false;
			lastName = (String) transfer.get("lastName");
			ok = Validator.validateString(lastName);
			if (ok == false) {
				lastNameMesage = "Please enter a real name!<br>(minim 3 alphabetical characters)";
				globalOk = false;
			}	else {System.out.println("a");}
		} catch (Exception e) {
			lastNameMesage = "Please enter a real name!<br>(minim 3 alphabetical characters)";
			globalOk = false;
		}
		
		try {
			ok = false;
			String dateString=(String)transfer.get("date");
			String[] aux=dateString.split("/");
			month=Integer.parseInt(aux[0]);
			day=Integer.parseInt(aux[1]);
			year=Integer.parseInt(aux[2]);
			date=new Date(year,month,day);
		} catch (Exception e) {
			dateMesage = "Please pick a date";
			globalOk = false;
		}
		
		
		try {
			ok = false;
			phoneNumber = (String) transfer.get("telNumber");
			ok = Validator.isNumeric(phoneNumber);
			if (ok == false) {
				phoneNumberMesage = "Please enter a valid phonenumber!<br>(minim 10 digits)";
				globalOk = false;
			}	else {System.out.println("a");}
		} catch (Exception e) {
			phoneNumberMesage = "Please enter a valid phonenumber!<br>(minim 10 digits)";
			globalOk = false;
		}
		
		try {
			ok = false;
			mobilePhoneNumber = (String) transfer.get("mobileNumber");
			ok = Validator.isNumeric(mobilePhoneNumber);
			if (ok == false) {
				mobilePhoneNumberMesage = "Please enter a valid phonenumber!<br>(minim 10 digits)";
				globalOk = false;
			}	else {System.out.println("a");}
		} catch (Exception e) {
			mobilePhoneNumberMesage = "Please enter a valid phonenumber!<br>(minim 10 digits)";
			globalOk = false;
		}
		
		
		try {
			ok = false;
			email = (String) transfer.get("email");
			ok = Validator.isValidEmailAddress(email);
			if (ok == false) {
				emailMesage = "Please enter a valid email!";
				globalOk = false;
			}	else {System.out.println("a");}
			email = (String) transfer.get("email");
		} catch (Exception e) {
			emailMesage = "Please enter a valid email!";
			globalOk = false;
		}
		

		try {
			address = (String) transfer.get("address");
		} catch (Exception e) {
			System.out.println("address exception");
		}		
		try {
			if (((String) transfer.get("relocation")) != null)
				relocate = true;
		} catch (Exception e) {
			System.out.println("relocate exception");
		}
		try {
			jobId = (String) transfer.get("jobId");
			job = jobService.getById(Long.parseLong(jobId));
		} catch (Exception e) {
			System.out.println("job exceptionoj oj oj oj");
		}


		Candidate candidate =candidateService.getById(id);
		candidate.setFirstName(firstName);
		candidate.setLastName(lastName);
		if(cv!=null){
		System.out.println("filename  "+filename);
		candidate.setCv(cv);
		candidate.setFileName(filename);
		}
		candidate.setDate(date);
		candidate.setComments(comments);
		candidate.setPhoneNumber(phoneNumber);
		candidate.setMobilePhoneNumber(mobilePhoneNumber);
		candidate.setEmail(email);
		candidate.setAddress(address);
		candidate.setRelocate(relocate);
	
	
		

		HttpSession session = request.getSession();
		
		if (globalOk == false) {
			if (jobId.length() > 0
					&& null != jobService.getById(Long.parseLong(jobId))) {
				
				System.out.println("cucc1");
				
				session.setAttribute("firstNameMesage", firstNameMesage);
				session.setAttribute("lastNameMesage", lastNameMesage);
				session.setAttribute("dateMesage", dateMesage);
				session.setAttribute("phoneNumberMesage", phoneNumberMesage);
				session.setAttribute("mobilePhoneNumberMesage",
						mobilePhoneNumberMesage);
				session.setAttribute("emailMesage", emailMesage);
				session.setAttribute("addressMesage", addressMesage);
				if (cv != null) {
					System.out.println("filename  "+filename);
					session.setAttribute("filename", filename);
				}
				session.setAttribute("candidate", candidate);
				session.setAttribute("candidateComment", commentText);
				session.setAttribute("jobId", jobId);
				session.setAttribute("up",userName);

				String address2 = "./updateCandidate.jsp";
				RequestDispatcher dispatcher = request
						.getRequestDispatcher(address2);
				dispatcher.forward(request, response);
			} else {
				
				System.out.println("cucc2");
				
				String address2 = "./error";
				RequestDispatcher dispatcher = request
						.getRequestDispatcher(address2);
				dispatcher.forward(request, response);
			}
		} else {
			
			candidateService.update(candidate);
			List<Candidate> list=candidateService.getAll();
			session.setAttribute("candidates", list);
			System.out.println("cucc3");
			session.setAttribute("job", job);
			session.setAttribute("firstNameMesage", "");
			session.setAttribute("lastNameMesage", "");
			session.setAttribute("dateMesage", "");
			session.setAttribute("phoneNumberMesage", "");
			session.setAttribute("mobilePhoneNumberMesage","");
			session.setAttribute("emailMesage", "");
			session.setAttribute("candidate", null);
			String address2 = "./showCandidates.jsp";
			RequestDispatcher dispatcher = request
					.getRequestDispatcher(address2);
			dispatcher.forward(request, response);
		}
	}

}
